package com.anysoft.web;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebView;

import com.anysoft.HostConstant;
import com.anysoft.R;
import com.anysoft.WebViewNetworkProtocol;
import com.anysoft.bean.AttentionsCommandBean;
import com.anysoft.bean.QueryAttentionByFundcodeBean;
import com.anysoft.event.FundBuyResultEvent;
import com.anysoft.event.TimeOutEvent;
import com.anysoft.home.HomeActivity;
import com.anysoft.me.base.BaseFundWebViewActivity;
import com.anysoft.me.config.CommentConfig;
import com.anysoft.utils.ActivityUtils;
import com.anysoft.utils.CommonUtil;
import com.anysoft.utils.HttpUtils;
import com.anysoft.utils.MentorLogger;
import com.anysoft.utils.PreferencesUtils;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

import butterknife.OnClick;

/**
 * Created by wwq on 2017/3/16.
 * 基金详情页面
 */

public class FundDetailActivity extends BaseFundWebViewActivity {

    private String fundcode;
    private String fundname;
    private String fundType;
    private String titleStr;
    private String subTitleStr;
    private String fundstateid;
    private String token = "";
    public boolean isFollow = false;
    private boolean isFromGuide = false;

    private boolean isFirstFundDetail = true; //是否是第一次进入

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (PreferencesUtils.getBoolean(this, CommentConfig.SPFlag.IS_FIRST_FUNDDETAIL)) {
            isFirstFundDetail = false;
        }
        PreferencesUtils.putBoolean(this, CommentConfig.SPFlag.IS_FIRST_FUNDDETAIL, true);
        MentorLogger.Loge("isFirstFundDetail=" + isFirstFundDetail);

        getIntentValue();
        rightButton.setVisibility(View.VISIBLE);
        cmtv_title.setText(titleStr);
        subTitle.setText(subTitleStr);
        String param = HttpUtils.getCommonParams2StringByWeb(mActivity) + "&fundCode=" + fundcode + "&fundName=" + fundname
                + "&cusNo=" + getFundCustomerNo() + "&fundstateid=" + fundstateid + "&fundType=" + fundType
                + "&isFirstFundDetail=" + isFirstFundDetail;
        generateUrl("fundDetail", param);

        if (!TextUtils.isEmpty(getFundCustomerNo())) {
            queryAttentionByFundcode();
        }
        if (!TextUtils.isEmpty(fundcode)) {
            queryFundInfo(fundcode);
        }

        if (CommonUtil.isNetWorkConnected(mActivity)) {
            setWebViewConfig(loadUrl);
        }
//        SharePopup.setOnShareEventLinstener(new OnShareEventLinstenerImpl() {
//            @Override
//            public void onShareSuccess() {
//                AnalyticsEventUtils.toShareFundEvent(FundDetailActivity.this);
//            }
//        });
    }

    private void getIntentValue() {
        fundcode = getIntent().getStringExtra("fundcode");
        fundname = getIntent().getStringExtra("fundname");
        fundType = getIntent().getStringExtra("fundType");
        titleStr = getIntent().getStringExtra("mainTitle");
        subTitleStr = getIntent().getStringExtra("subTitle");
        fundstateid = getIntent().getStringExtra("fundstateid");
        isFromGuide = getIntent().getBooleanExtra("isFromGuide", false);
        token = getToken();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!token.equals(getToken())) {
            token = getToken();
            generateUrl("fundDetail", HttpUtils.getCommonParams2StringByWeb(mActivity) + "&fundCode=" +
                    fundcode + "&fundName=" + fundname + "&cusNo=" + getFundCustomerNo() + "&fundstateid=" + fundstateid + "&fundType=" + fundType
                    + "&isFirstFundDetail=" + isFirstFundDetail);
            reLoadPage(loadUrl);
        }

        if (!TextUtils.isEmpty(getFundCustomerNo())) {
            queryAttentionByFundcode();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    /**
     * 查询某个关注的基金
     */
    private void queryAttentionByFundcode() {
        Map<String, String> params = new HashMap<>();
        params.put("fundCustomerNo", getFundCustomerNo());
        params.put("fundCode", fundcode);
        OkGo.<String>post(HostConstant.QUERY_ATTENTIONS_BY_FUNDCODE)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        UpdateUI(response.body());
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast("网络加载失败，请稍后再试!");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    private void UpdateUI(String resultJson) {

        QueryAttentionByFundcodeBean bean;

        try {
            bean = new Gson().fromJson(resultJson, QueryAttentionByFundcodeBean.class);
        } catch (Exception e) {
            Logger.e(TAG, "Gson解析数据时发生异常");
            e.printStackTrace();
            return;
        }

        if (!CommonUtil.checkState(mActivity, bean, resultJson)) {
            return;
        }

        if (bean.getData() == null) {
            showConfirmAlert(mActivity, "数据为空");
            return;
        }

        switch (bean.getData().getIsAttention()) {
            case 0:
                isFollow = false;
                rightButton.setBackgroundResource(R.mipmap.nav_like_white);
                break;
            case 1:
                isFollow = true;
                rightButton.setBackgroundResource(R.mipmap.nav_like_ac_white);
                break;
            default:
                break;
        }

    }

    @Override
    public void onshouldOverrideUrlLoadingCallBack(WebView webview, String url) {
        MentorLogger.Log(TAG, "CallBack url=" + url);

        String url_decode = null;
        try {
            url_decode = URLDecoder.decode(url, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        MentorLogger.Log(TAG, "url_decode=" + url_decode);
        String mainTitle;
        String infoTitle;
        Map<String, String> map = new HashMap<>();
        String[] params = url_decode.split("\\?")[1].split("&");
        for (int i = 0; i < params.length; i++) {
            String key = params[i].split("=")[0];
            String value = "";
            try {
                value = params[i].split("=")[1];
            } catch (Exception exception) {
                MentorLogger.Log(TAG, "value为null");
            }
            map.put(key, value);
        }
        mainTitle = map.get("fundName") + " " + map.get("fundCode");
        infoTitle = map.get("infoTitle");

        if (url.contains("prompt.html")) {
            mIntent.setClass(mActivity, SelectWarmPromptActivity.class);
            mIntent.putExtra("url", url);
            startActivity(mIntent);
        } else if (url.contains("fundBuy.html")) { //购买
            mIntent.setClass(mActivity, AssetsFundBuyActivity.class);
            String param = url.split("\\?")[1];
            mIntent.putExtra("param", param);
            mIntent.putExtra("mainTitle", mainTitle);
            startActivity(mIntent);
        } else if (url.contains("fundInvest.html")) {
            mIntent.setClass(mActivity, AssetsFundInvestActivity.class);
            String param = url.split("\\?")[1];
            mIntent.putExtra("param", param);
            mIntent.putExtra("mainTitle", mainTitle);
            startActivity(mIntent);
        } else if (url.contains("fundInvestAdd.html")) {
            mIntent.setClass(mActivity, AssetsFundInvestAddActivity.class);
            String param = url.split("\\?")[1];
            mIntent.putExtra("param", param);
            mIntent.putExtra("mainTitle", mainTitle);
            startActivity(mIntent);
        } else if (url.contains("tradingInformation.html")) { //交易信息
            mIntent.setClass(mActivity, FundDetailCommentActivity.class);
            String param = url.split("\\?")[1];
            mIntent.putExtra("param", param);
            mIntent.putExtra("fundName", fundname);
            mIntent.putExtra("fundCode", fundcode);
            mIntent.putExtra("subTitleStr", subTitleStr);
            mIntent.putExtra("infoTitle", "交易信息");
            mIntent.putExtra("url_title", "tradingInformation");
            startActivity(mIntent);
        } else if (url.contains("earnings.html")) { //更多收益和查看更多
            mIntent.setClass(mActivity, FundDetailCommentActivity.class);
            String param = url.split("\\?")[1];
            mIntent.putExtra("param", param);
            mIntent.putExtra("fundName", fundname);
            mIntent.putExtra("fundCode", fundcode);
            mIntent.putExtra("subTitleStr", subTitleStr);
            mIntent.putExtra("infoTitle", "");
            mIntent.putExtra("url_title", "earnings");
            startActivity(mIntent);

        } else if (url.contains("fundFile.html")) { //基金档案 和基金经理
            mIntent.setClass(mActivity, FundDetailCommentActivity.class);
            String param = url.split("\\?")[1];
            mIntent.putExtra("param", param);
            mIntent.putExtra("url_title", "fundFile");
            mIntent.putExtra("fundName", fundname);
            mIntent.putExtra("fundCode", fundcode);
            mIntent.putExtra("subTitleStr", subTitleStr);
            mIntent.putExtra("infoTitle", infoTitle);
            startActivity(mIntent);

        } else if (url.contains("fundScalePortio.html")) { //规模份额 3.0.8新增
            mIntent.setClass(mActivity, FundDetailCommentActivity.class);
            String param = url.split("\\?")[1];
            mIntent.putExtra("param", param);
            mIntent.putExtra("url_title", "fundScalePortio");
            mIntent.putExtra("fundName", fundname);
            mIntent.putExtra("fundCode", fundcode);
            mIntent.putExtra("subTitleStr", subTitleStr);
            mIntent.putExtra("infoTitle", "规模份额");
            startActivity(mIntent);
        } else if (url.contains("portfolio.html")) { //投资组合 3.0.8 fundDetailInfo 改为portfolio
            mIntent.setClass(mActivity, FundDetailCommentActivity.class);
            String param = url.split("\\?")[1];
            mIntent.putExtra("param", param);
            mIntent.putExtra("fundName", fundname);
            mIntent.putExtra("fundCode", fundcode);
            mIntent.putExtra("subTitleStr", subTitleStr);
            mIntent.putExtra("infoTitle", "投资组合");
            mIntent.putExtra("url_title", "portfolio");
            startActivity(mIntent);
        } else if (url.contains("sameTypeFund.html")) { //同类型基金
            mIntent.setClass(mActivity, FundDetailCommentActivity.class);
            String param = url.split("\\?")[1];
            mIntent.putExtra("param", param);
            mIntent.putExtra("url_title", "sameTypeFund");
            mIntent.putExtra("fundName", fundname);
            mIntent.putExtra("fundCode", fundcode);
            mIntent.putExtra("subTitleStr", subTitleStr);
            mIntent.putExtra("infoTitle", "同类型基金");
            startActivity(mIntent);
        } else if (url.contains("fundHistoryShare.html")) { //历史分红  3.0.8新增
            mIntent.setClass(mActivity, FundDetailCommentActivity.class);
            String param = url.split("\\?")[1];
            mIntent.putExtra("param", param);
            mIntent.putExtra("url_title", "fundHistoryShare");
            mIntent.putExtra("fundName", fundname);
            mIntent.putExtra("fundCode", fundcode);
            mIntent.putExtra("subTitleStr", subTitleStr);
            mIntent.putExtra("infoTitle", "历史分红");
            startActivity(mIntent);
        } else if (url.contains("fundAnnoumentnce.html")) { //基金公告  3.0.8新增
            mIntent.setClass(mActivity, FundDetailCommentActivity.class);
            String param = url.split("\\?")[1];
            mIntent.putExtra("param", param);
            mIntent.putExtra("url_title", "fundAnnoumentnce");
            mIntent.putExtra("fundName", fundname);
            mIntent.putExtra("fundCode", fundcode);
            mIntent.putExtra("subTitleStr", subTitleStr);
            mIntent.putExtra("infoTitle", "基金公告");
            startActivity(mIntent);
        } else if (url.contains("fundHistory")) {
            mIntent.setClass(mActivity, FundDetailHistoryActivity.class);
            String param = url.split("\\?")[1];
            mIntent.putExtra("param", param);
            startActivity(mIntent);
        } else if (url.contains(WebViewNetworkProtocol.GOTO_LOGIN)) {
            ActivityUtils.gotoLogin(mActivity, hasUser(), false, findUserId());
        } else if (url.contains(WebViewNetworkProtocol.GO_QUESTION)) {
            startRiskActivity(null);
        } else if (url.contains(WebViewNetworkProtocol.GOTO_E_CHART)) { //横屏
            mIntent.setClass(mActivity, FundDetailEchartActivity.class);
            String param = url.split("\\?")[1];
            mIntent.putExtra("param", param);
            startActivity(mIntent);
        } else if (url.contains(WebViewNetworkProtocol.GO_MOD_USER_INFO)) {
            ActivityUtils.gotoUserInfoMod(mActivity, MOD_USER_INFO);
        } else if (url.contains(WebViewNetworkProtocol.GO_EDIT_MOBILE)) {
            ActivityUtils.gotoUserMobileMod(mActivity, MOD_USER_MOBILE);
        } else {
            webview.loadUrl(url);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGestureSetCallBack(FundBuyResultEvent event) {
        if (event.isSuccess) {
            reLoadPage(loadUrl);
        }
    }

    @OnClick({R.id.leftButton, R.id.rightButton, R.id.shareButton})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.leftButton:
                if (isFromGuide) {
                    startActivity(new Intent().setClass(mActivity, HomeActivity.class));
                }
                finish();
                break;
            case R.id.rightButton:
                if (!isFastDoubleClick()) {
                    if (mentorApplication.needLogin()) {
                        ActivityUtils.gotoLogin(mActivity, hasUser(), false, findUserId());
                    } else {
                        if (isFollow) {
                            attentionsCommand(0);
                        } else {
                            attentionsCommand(1);
                        }
                    }
                }
                break;
            case R.id.shareButton:
                if (!isFastDoubleClick()) {
                    //请求查询基金接口获取近一年收益值
                    String periodYearOne = getFundPeriodYearOne();
                    //TODO 需要H5对应连接地址
                    String url = HostConstant.HOST_WEB_URL_HEADER + String.format("fundDetailSec.html?fundCode=%s&fundType=%s", fundcode, fundType);
//                    SharePopup.Share(mActivity, mActivity.getResources().getString(R.string.share_title), url, fundname + " " +
//                            "" + fundcode + "\n近一年收益率" + periodYearOne);
                }
                break;
        }
    }

    /**
     * 取消/添加关注
     *
     * @param action 0为取消关注，１为添加关注
     */
    private void attentionsCommand(int action) {
        Map<String, String> params = new HashMap<>();

        params.put("fundCustomerNo", getFundCustomerNo());
        params.put("fundCode", fundcode);
        params.put("action", action + "");
        OkGo.<String>post(HostConstant.ATTENTIONS_COMMAND)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new com.lzy.okgo.callback.StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        MentorLogger.LogJson(TAG + "取消/添加关注:", response.body());
                        UpdateAttentionsCommand(response.body());
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast("网络加载失败，请稍后再试!");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    private void UpdateAttentionsCommand(String json) {

        AttentionsCommandBean bean;
        try {
            bean = new Gson().fromJson(json, AttentionsCommandBean.class);
        } catch (Exception exception) {
            showConfirmAlert(mActivity, "提示", "数据解析错误");
            return;
        }

        if (!CommonUtil.checkState(mActivity, bean, json)) {
            return;
        }

        if (bean.isData()) {
            if (isFollow) {
                isFollow = false;
                rightButton.setBackgroundResource(R.mipmap.nav_like_white);
                showToast("取消关注成功");
            } else {
                isFollow = true;
                rightButton.setBackgroundResource(R.mipmap.nav_like_ac_white);
                showToast("添加关注成功");
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTimeOutCallBack(TimeOutEvent event) {
        if (event.isSuccess) {
            if (isFromGuide) {
                startActivity(new Intent().setClass(mActivity, HomeActivity.class));
                finish();
            }
        }
    }

    @Override
    public void onBackPressed() {
        if (isFromGuide) {
            startActivity(new Intent().setClass(mActivity, HomeActivity.class));
        }
        super.onBackPressed();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        if (MOD_USER_INFO == requestCode || MOD_USER_MOBILE == requestCode) {
            token = getToken();
            generateUrl("fundDetail", HttpUtils.getCommonParams2StringByWeb(mActivity) + "&fundCode=" + fundcode +
                    "&fundName="
                    + fundname
                    + "&cusNo=" + getFundCustomerNo() + "&fundstateid=" + fundstateid);

            if (CommonUtil.isNetWorkConnected(mActivity)) {
                reLoadPage(loadUrl);
            }
            if (!TextUtils.isEmpty(getFundCustomerNo())) {
                queryAttentionByFundcode();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
